package com.shi.yoyoshop.controller;

import com.shi.yoyoshop.bean.Admin;
import com.shi.yoyoshop.dto.AdminLoginDto;
import com.shi.yoyoshop.dto.AdminUpdatePasswordDto;
import com.shi.yoyoshop.service.AdminService;
import com.shi.yoyoshop.util.SafeUtil;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
public class AdminController {

    @Resource
    private AdminService adminService;

    @PostMapping("/admin/login")
    public String login(HttpServletRequest request, AdminLoginDto adminLoginDto) {
        Admin admin=adminService.getAdminByUsername(adminLoginDto.getUsername());
        if (ObjectUtils.isEmpty(admin)) {
            request.setAttribute("msg", "用户名不存在");
            return "/admin/login.jsp";
        }
        if (!admin.getPassword().equals(SafeUtil.encode(adminLoginDto.getPassword()))) {
            request.setAttribute("msg", "密码不正确");
            return "/admin/login.jsp";
        }
        request.getSession().setAttribute("admin", admin);
        return "/admin/index.jsp";
    }

    @GetMapping("/admin/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:/admin/login.jsp";
    }

    @GetMapping("/admin/adminRe")
    public String toUpdatePassword(HttpServletRequest request) {
        request.setAttribute("flag", 5);
        return "/admin/admin_reset.jsp";
    }

    @PostMapping("/admin/adminRe")
    public String updatePassword(HttpServletRequest request, AdminUpdatePasswordDto updatePasswordDto) {
        String passwordFromReq = SafeUtil.encode(updatePasswordDto.getPassword());
        Admin admin = (Admin) request.getSession().getAttribute("admin");
        if (!admin.getPassword().equals(passwordFromReq)) {
            request.setAttribute("msg", "旧密码错误");
            return "/admin/admin_reset.jsp";
        } else {
            adminService.updatePasswordById(SafeUtil.encode(updatePasswordDto.getPasswordNew()),updatePasswordDto.getId());
            return "/admin/login.jsp";
        }
    }
}
